package Demo;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

class MyTask implements Comparable<MyTask>{
    // 要执行的任务
    private Runnable runnable;
    // 时间
    private long time;

    public MyTask(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}
public class MyTimer {
    private BlockingQueue<MyTask> blockingQueue = new PriorityBlockingQueue<>();

    private Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(()->{
           while(true){
               try {
                   synchronized (locker) {
                       MyTask myTask = blockingQueue.take();
                       // 当前时间是否大于等于要执行任务的时间
                       if (System.currentTimeMillis() >= myTask.getTime()){
                           // 时间到了 执行任务
                           myTask.getRunnable().run();
                       }else {
                           // 时间没到,再把任务放回阻塞队列中
                           blockingQueue.put(myTask);
                           // 进行等待
                           locker.wait(myTask.getTime()-System.currentTimeMillis());
                       }
                   }
               } catch (InterruptedException e) {
                   throw new RuntimeException(e);
               }
           }
        });
        t.start();
    }

    public void schedule(Runnable runnable, long time) throws InterruptedException {
        MyTask myTask = new MyTask(runnable,time);
        blockingQueue.put(myTask);
        synchronized (locker) {
            locker.notify();
        }
    }
}
